package xcmg.device.service.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.file.FtpParam;
import xcmg.device.infra.exception.CommonBusiExceptions;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;


/**
 * ftp上传文件 后台接口实现类
 */
@Slf4j
@Service
public class FtpService {



    @Autowired
    private FtpParam ftpParam;
    private static final String FILE_SPLIT = "/";

    /**
     * 初始化ftp服务器
     */
    public FTPClient initFtpClient() {
        long t = System.currentTimeMillis();
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ftpParam.getHostname(), ftpParam.getPort());
            ftpClient.login(ftpParam.getUsername(), ftpParam.getPassword());
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.info("connect failed...ftp服务器:" + ftpParam);
            }
            log.info("connect successfu...ftp服务器:{}, time:{}", ftpParam, (System.currentTimeMillis() - t));
            return ftpClient;
        } catch (Exception e) {
            log.error("connect error...ftp服务器:" + ftpParam);
            throw new CommonBusiExceptions("错误：connect ftp服务器 error..." + e.getMessage());
        }
    }

    public String uploadFile(File tmpFile, String parentPath) {
        long t = System.currentTimeMillis();
        String pathname = null;
        if (StringUtils.isBlank(parentPath)) {
            pathname = "BJ"+ FILE_SPLIT + LocalDate.now().getYear() + FILE_SPLIT + LocalDate.now().getMonthValue() + FILE_SPLIT + LocalDate.now().getDayOfMonth();
        } else {
            pathname = parentPath;
        }
        FTPClient ftpClient = initFtpClient();
        try (FileInputStream inputStream = new FileInputStream(tmpFile)){
            log.info("开始上传文件");
            createDirecroty(pathname, ftpClient);
            String fileName = tmpFile.getName();
            ftpClient.setControlEncoding("utf-8");//设置ftp字符集
            ftpClient.enterLocalPassiveMode();//设置被动模式，文件传输端口设置  服务器端开启随机接口
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置文件传输模式为二进制，保证传输内容不会被改变
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            boolean result = ftpClient.storeFile(fileName, inputStream);
            if (!result) {
                log.info("上传文件返回失败，准备返回文件地址,pathname:{}", pathname);
                return null;
            }
            ftpClient.logout();
            log.info("上传文件完成，准备返回文件地址,pathname:{}", pathname);
            return pathname + FILE_SPLIT + fileName;
        } catch (Exception e) {
            log.error("cn.com.xgit.platform.storage.module.file.service.impl.FtpServiceImpl.uploadFile error", e);
            throw new CommonBusiExceptions("上传文件错误：" + e.getMessage());
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
            log.info("uploadFile  time:{}", (System.currentTimeMillis() - t));
        }
    }

    private boolean createDirecroty(String remote, FTPClient ftpClient) throws IOException {
        boolean success = true;

        String directory = remote + FILE_SPLIT;
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase(FILE_SPLIT) && !changeWorkingDirectory(directory, ftpClient)) {
            int start = 0;
            int end = 0;
            if (directory.startsWith(FILE_SPLIT)) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf(FILE_SPLIT, start);
            StringBuilder path = new StringBuilder();
            StringBuilder paths = new StringBuilder();
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
                path = path.append(FILE_SPLIT).append(subDirectory);
                if (!existFile(path.toString(), ftpClient)) {
                    if (makeDirectory(subDirectory, ftpClient)) {
                        changeWorkingDirectory(subDirectory, ftpClient);
                    } else {
                        log.info("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory, ftpClient);
                    }
                } else {
                    changeWorkingDirectory(subDirectory, ftpClient);
                }

                paths.append(FILE_SPLIT).append(subDirectory);
                start = end + 1;
                end = directory.indexOf(FILE_SPLIT, start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //改变目录路径
    public boolean changeWorkingDirectory(String directory, FTPClient ftpClient) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                log.info("进入文件夹" + directory + " 成功！");

            } else {
                log.info("进入文件夹" + directory + " 失败！开始创建文件夹");
            }
        } catch (IOException ioe) {
            log.error("", ioe);
        }
        return flag;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path, FTPClient ftpClient) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //创建目录
    public boolean makeDirectory(String dir, FTPClient ftpClient) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                log.info("创建文件夹" + dir + " 成功！");

            } else {
                log.info("创建文件夹" + dir + " 失败！");
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return flag;
    }

    /**
     * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @param localpath 下载后的文件路径 *
     * @return
     */
    public boolean downloadFile(String pathname, String filename, String localpath) {
        boolean flag = false;
        FTPClient ftpClient = initFtpClient();
        try {
            log.info("开始下载文件");
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    File localFile = new File(localpath + FILE_SPLIT + file.getName());
                    try (OutputStream os = new FileOutputStream(localFile)){
                        ftpClient.retrieveFile(file.getName(), os);
                    }
                }
            }
            ftpClient.logout();
            flag = true;
            log.info("下载文件成功");
        } catch (Exception e) {
            log.info("下载文件失败");
            log.error("", e);
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        return flag;
    }

    /**
     * 获取文件流 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @return
     */
    public InputStream downloadFile(String pathname, String filename) {
        InputStream in = null;
        FTPClient ftpClient = initFtpClient();
        try {
            log.info("开始下载文件");
            ftpClient.setControlEncoding("utf-8");//设置ftp字符集
            ftpClient.enterLocalPassiveMode();//设置被动模式，文件传输端口设置  服务器端开启随机接口
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置文件传输模式为二进制，保证传输内容不会被改变
            //切换FTP目录
            if (!ftpClient.changeWorkingDirectory(pathname)) {
                throw new CommonBusiExceptions("路径错误");
            }
            in = ftpClient.retrieveFileStream(URLEncoder.encode(filename, "UTF-8"));
            if (in == null) {
                throw new CommonBusiExceptions("文件不存在");
            }
            ftpClient.logout();
            log.info("下载文件成功");
        } catch (Exception e) {
            log.error("下载文件错误：{}", e.getMessage());
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        return in;
    }

    /**
     * 获取文件流 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @return
     */
    public void downloadFile(String pathname, String filename, OutputStream ous) {
        FTPClient ftpClient = initFtpClient();
        try {
            log.info("开始下载文件");
            ftpClient.setControlEncoding("utf-8");//设置ftp字符集
            ftpClient.enterLocalPassiveMode();//设置被动模式，文件传输端口设置  服务器端开启随机接口
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置文件传输模式为二进制，保证传输内容不会被改变
            //切换FTP目录
            if (!ftpClient.changeWorkingDirectory(pathname)) {
                throw new CommonBusiExceptions("路径错误");
            }
            InputStream in = ftpClient.retrieveFileStream(URLEncoder.encode(filename, "UTF-8"));
            if (in == null) {
                throw new CommonBusiExceptions("文件不存在");
            }
            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) > 0) {
                ous.write(buffer,0, bytesRead);
            }
            in.close();
            ous.flush();
            ftpClient.logout();
            log.info("下载文件成功");
        } catch (Exception e) {
            log.error("下载文件错误：{}", e.getMessage());
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
    }

    /**
     * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    public boolean deleteFile(String pathname, String filename, FTPClient ftpClient) {
        boolean flag = false;
        try {
            log.info("开始删除文件");
            ftpClient = initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            log.info("删除文件成功");
        } catch (Exception e) {
            log.error("删除文件失败", e);
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        return flag;
    }

}
